var utils = require("./utils/utils");
App({
  globalData: {
    nickName: "",
    avatarUrl: "",
    globalUrl: "https://mini.kuchengxiche.cn/",
    useTime: 330
  },
  onHide(){
    wx.removeStorageSync('code');
  },
  onShow(e) {
    var query = decodeURIComponent(e.query.scene);
    var p_id, device_qrcode_id;
    if (query && query.split(",")[1]) {
      device_qrcode_id = query.split(",")[1];
      wx.setStorageSync("code", device_qrcode_id);
    } else if (query) {
      p_id = query;
      wx.setStorageSync("p_id", p_id);
    }
  },
  onLaunch(e) {
    // console.log(Math.floor(new Date().getTime() / 1000))
    // console.log(e)       
    // var query = decodeURIComponent(e.query.scene);
    // var p_id , device_qrcode_id;
    // if (query && query.split(",")[1]){
    //   device_qrcode_id = query.split(",")[1];
    //   wx.setStorageSync("code", device_qrcode_id);
    // } else if (query){
    //   p_id = query;
    //   wx.setStorageSync("p_id", p_id);
    // }
    // 展示本地存储能力
    this.utils = utils;
    // var u_id = wx.getStorageSync('u_id');
    // if (!u_id) {
    //   wx.redirectTo({
    //     url: 'pages/login/login'
    //   })
    // }
  },
  // 公用登录方法
  getUserInfoFun() {
    var u_id = wx.getStorageSync('user').u_id;
    var that = this;
    if (!u_id) {
      wx.redirectTo({
        url: '/pages/login/login'
      })
    }

  },
  // // 获取默认车辆信息
  // getUsercar(u_id, that) {
  //   var data = {
  //     u_id: u_id
  //   };
  //   var checkUrl = "obd/Cardetection/check.html";
  //   var checkCallback = res => {
  //     that.setData({
  //       checkCar: res.code
  //     });
  //     var data = res.data;
  //     wx.setStorageSync("status", data);
  //     var logoImg = "";
  //     if (res.code != 200) {
  //       return;
  //     }
  //     if (data.defaultcar.logo) {
  //       logoImg = this.globalData.globalUrl + data.defaultcar.logo;
  //     } else {
  //       logoImg = "../../images/index/images/che_logo.png";
  //     }
  //     that.setData({
  //       defaultCar_img: logoImg
  //     });
  //     wx.setStorageSync("defaultCar_img", logoImg);
  //     wx.setStorageSync("c_id", data.defaultcar.c_id);
  //     wx.setStorageSync("Carlicense", data.Carlicense);
  //     wx.setStorageSync("Insurance", data.Insurance);
  //     wx.setStorageSync("License", data.License);
  //     wx.setStorageSync("Upkeep", data.Upkeep);
  //     wx.setStorageSync("licenseplate", data.defaultcar.licenseplate);
  //     wx.setStorageSync("cell", data.cell);
  //     wx.setStorageSync("engine", data.engine);
  //     wx.setStorageSync("point", data.point);
  //     wx.setStorageSync("o_id", data.defaultcar.o_id);
  //     that.setData({
  //       licenseplate: data.defaultcar.licenseplate
  //     });
  //   };
  //   this.getRequest(checkUrl, data, checkCallback);
  // },
  // 封装的ajax
  getRequest(url, data, callback, type = "post",showLoading=true) {
    showLoading && wx.showLoading({
      title: "请求数据中！"
    });
    this.reqtime = new Date().getTime();
    wx.request({
      url: this.globalData.globalUrl + url,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      data: data,
      success: res => {
        if (res.statusCode == 200 && res.data.code != 200) {
          // wx.showToast({
          //   title: res.data.message?res.data.message:'',
          //   icon: "none"
          // });
        }
        typeof callback === "function" && callback(res.data);
      },
      fail: () => {
        wx.showToast({
          title: "发生未知错误！"
        });
      },
      complete: () => {
        if (new Date().getTime() - this.reqtime < 8000) {
          setTimeout(() => {
            wx.hideLoading();
          }, 500);
        } else {
          wx.hideLoading();
        }
      }
    });
  },
  getRequestSync(url, data, callback, type = "post") {
    wx.showLoading({
      title: "指令发送成功，等待获取执行结果！",
      mask:true
    });
    this.reqtime = new Date().getTime();
    setTimeout(()=>{
      this.requestMnst(url, data, callback, 0);
    },2000);
    
  },
  /**
   * 请求操作结果
   * 
   */
  requestMnst(url, datas, callback,num) {
    num = num + 1;
    var that = this;
    wx.request({
      url: this.globalData.globalUrl + url,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      data: datas,
      success: res => {
        if (res.statusCode == 200 && res.data.code != 200) {
          // wx.showToast({
          //   title: res.data.message?res.data.message:'',
          //   icon: "none"
          // });
        } 
        if (res.data.code != 200 && num < 5) {
          setTimeout(()=>{
            that.requestMnst(url, datas, callback, num);
          },2000);
        } else if (res.data.code == 200) {
          typeof callback === "function" && callback(res.data);
        } else if (res.data.code != 200 && num == 5) {
          wx.showModal({
            title: '',
            content: res.data.message + "请重试",
            showCancel:false
          });
          callback({data:res.data,noMessage:"ss"});
          // that.getStatus(datas.device_id, datas.product_iot_id, function(res){
          //   callback({ code: 2020, msgid:res})
          // })
        }
        // typeof callback === "function" && callback(res.data);
      },
      fail: () => {
        wx.showToast({
          title: "发生未知错误！"
        });
      },
      complete: () => {
        setTimeout(() => {
          wx.hideLoading();
        }, 8000);
        // if (new Date().getTime() - this.reqtime < 8000) {
        //   setTimeout(() => {
        //     wx.hideLoading();
        //   }, 8000);
        // } else {
        //   wx.hideLoading();
        // }
      }
    });
  },
  // 公共login方法
  Login(that, cb) {
    var this_ = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          var jscode = res.code;
          wx.getUserInfo({
            success: function (res_) {
              var userInfo = res_.userInfo;
              wx.setStorageSync("userInfo", userInfo);
              that.setData({
                eye: true
              });
              this_.getRequest(
                "api/login/getOpenid", {
                  js_code: jscode
                },
                function (res_user) {
                  var unionid = res_user.unionid ? res_user.unionid : "";
                  var userId = res_user.openid;
                  wx.setStorageSync("openId", userId);
                  wx.setStorageSync("unionid", unionid);
                  if (res_user.needPhone == 0) {
                    userInfo.openid = userId;
                    userInfo.unionid = unionid;
                    var phone = wx.getStorageSync("phone");
                    phone = phone ? phone : "";
                    userInfo.phone = phone;
                    this_.getRequest("api/login/userlogin", userInfo, function (
                      rres
                    ) {
                      if (rres.code == 200) {
                        wx.setStorageSync("u_id", rres.data.u_id);
                        wx.setStorageSync("nickName", rres.data.nickName);
                        wx.setStorageSync("avatarUrl", rres.data.head_pic);
                        wx.setStorageSync("sex", rres.data.sex);
                        wx.setStorageSync("phone", rres.data.phone);
                        var u_id = rres.data.u_id;
                        cb(u_id);
                      }
                    });
                  } else {
                    that.setData({
                      hasTele: false
                    });
                  }
                }
              );
            }

          });
        }
      }
    });
  },
  /**
   * 将时间戳转换成年月日
   */
  time: function(data){
    var date = new Date();
    date.setTime(data * 1000);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    
    //返回年月日时分秒
    // return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second; 

    return y + '-' + m + '-' + d;
  },
  /**
   * // 查询设备状态和汽车停放状态
   */
  getStatus: function (device_id, product_iot_id, callBack,thisnum=0) {
    var that = this;
    var status = 0;
    that.getRequest("api/device/putStatus", { device_id: device_id, product_iot_id: product_iot_id }, function (e) {
      if (e.code == 200) {
        var msgId = e.data.msgId;
        callBack(msgId)
      } else if (thisnum < 6 && e.code == 205) {
        wx.showToast({
          title: thisnum + "秒内得到结果！",
          icon: "none"
        });
        thisnum++;
        setTimeout(() => {
          that.getStatus(device_id, product_iot_id, callBack, thisnum);
        }, 1000);
      }else {
        wx.showToast({
          title: e.message,
          icon: "none"
        })
        // status = 2;
        // callBack(e.message)
      }
    })
    // return status;
  },
  getStatusByMsg: function (device_id, product_iot_id, callBack,thisnum = 0) {
    var that = this;
    var status = 0;
    that.getRequest("api/device/putStatus", { device_id: device_id, product_iot_id: product_iot_id }, function (e) {
      if (e.code == 200) {
        var msgId = e.data.msgId;
        that.getRequestSync("api/device/mnstest", { msgid: msgId, device_id: device_id, product_iot_id: product_iot_id }, function (res) {
          if (res.code == 200) {
            if (res.data.faultInfo == "fault") {
              wx.showModal({
                title: '警告',
                content: '设备故障',
                showCancel: false
              })
            } else {
              if (res.data.carInPlace == "carNotInPlace") {
                wx.showModal({
                  title: '警告',
                  content: '请将车停至指定位置',
                  showCancel: false
                })
              } else {
                status = 1;
                console.log("one");
                callBack(status);
              }
            }
          } else {
            // wx.showToast({
            //   title: res.message,
            //   icon: "none"
            // })
            status = 1;
            console.log("two");            
            callBack(status);
          }
        })
      }else if(thisnum < 6 && e.code == 205){
        wx.showToast({
          title: thisnum+"秒内得到结果！",
          icon: "none"
        });
        thisnum ++;
        setTimeout(()=>{
          that.getStatusByMsg(device_id, product_iot_id, callBack, thisnum);
        },1000);
      } else {
        wx.showToast({
          title: e.message,
          icon: "none"
        })
        // status = 2;
        // callBack(e.message)
      }
    })
    // return status;
  }
});